<?php

namespace App\Console\Commands\Mybank;

use App\Kuafu\Mybank\Enum\MybankIncomeCacheEnum;
use App\Kuafu\Mybank\Model\MybankOrderRecordModel;
use App\Kuafu\Mybank\Model\MybankShopBindModel;
use App\Kuafu\Mybank\Service\MybankBrokerageService;
use App\Kuafu\Order\Model\OrderRecordModel;
use App\Kuafu\Pay\Model\PayStreamModel;
use App\Kuafu\Pay\Model\ShopPaymentModel;
use App\Kuafu\Shop\Model\ShopPaymentsModel;
use App\Kuafu\Shop\Service\ShopService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class RefreshShopIncomeCommand extends Command
{
    protected $signature = 'mybank:refresh-shop-income';

    protected $description = '刷新绑定的门店的总实收金额';

    public function handle()
    {
        $this->info(date('Y-m-d H:i:s') . '开始');
        // 获取所有的绑定的门店信息
        MybankShopBindModel::query()->get()->each(
            function ($item) {
                // 删除所有
//                MybankBrokerageService::forgetShopAllIncomeMonthCache($item->shopId);
                // 重新获取
                MybankBrokerageService::getShopAllIncomeMonthWithCache($item->shopId, '', true);
            }
        );

        $this->info('当月总实收金额已经刷新完成');

        // 判断是否存存在满额抽佣停止的情况
        $this->dealMaxBrokerage();

        $this->info('满额抽佣记录刷新成功');
        $this->info(date('Y-m-d H:i:s') . '结束');
    }

    public function dealMaxBrokerage()
    {
        ShopPaymentModel::query()
                        ->where('payChannel', PayStreamModel::PAY_CHANNEL_MYBANK_CONFIG)
                        ->whereRaw("payConfig -> '$.isStop' = false")
                        ->get()
                        ->each(function ($item) {
                            // 查询这个门店的佣金是否超过指定点数
                            $shopId = $item->shopId;

                            // 查询这个门店的所有扣款金额
                            $sumNetPaidAmount = MybankOrderRecordModel::query()
                                                                      ->where('shopId', $shopId)
                                                                      ->where('type',
                                                                          MybankOrderRecordModel::TYPE_BROKERAGE)
                                                                      ->where('payStatus',
                                                                          MybankOrderRecordModel::PAY_STATUS_PAID)
                                                                      ->sum('netPaidAmount');

                            $rule = $item->payConfig;
                            $rule = json_decode($rule, 1);

                            if (empty($rule)) {
                                Log::channel('mybank')->error(
                                    '查询总抽佣金额异常-支付配置有异常',
                                    [
                                        'shopId'       => $shopId,
                                        'fsNotifyUids' => [
                                            '3fgc8798'
                                        ]
                                    ]
                                );
                                return;
                            }

                            // 是否存在暂停规则
                            if (empty($rule['pauseRule'])) {
                                // TODO 处理暂停逻辑
                            }


                            // 是否存在停止规则
                            if (empty($rule['stopRule'])) {
                                return;
                            }

                            $this->info('检查门店: ' . $shopId);

                            // 获取最大金额
                            $stopTotalAmount = $rule['stopRule']['totalAmount'] ?? 0;

                            if (empty($stopTotalAmount)) {
                                Log::channel('mybank')->error(
                                    '查询总抽佣金额异常-结束金额异常',
                                    [
                                        'shopId'       => $shopId,
                                        'fsNotifyUids' => [
                                            '3fgc8798'
                                        ]
                                    ]
                                );
                                return;
                            }

                            // 判断是否超过最大的金额
                            $shopInfo = ShopService::getShopInfo($shopId);
                            if (bccomp($sumNetPaidAmount, $stopTotalAmount) >= 0) {
                                $rule['isStop']  = true;
                                $rule['stopLog'] = [
                                    'stopAt'         => date('Y-m-d H:i:s'),
                                    'stopRuleAmount' => $stopTotalAmount,
                                    'shopInfo'       => [
                                        'shopId'   => $shopId,
                                        'shopName' => $shopInfo->name,
                                        'shopCode' => $shopInfo->shopCode
                                    ]
//                                    'sumNetPaidAmount' => $sumNetPaidAmount,
//                                    'needRefundAmount' => (int)$sumNetPaidAmount - (int)$stopTotalAmount
                                ];
                                $ruleJson        = json_encode($rule);
                                $item->payConfig = $ruleJson;
                                $item->save();

                                Log::channel('mybank')->notice('商户抽佣满额, 停止抽佣',
                                    $rule['stopLog'] +
                                    [
                                        'fsNotifyUids' => [
                                            '3fgc8798'
                                        ]
                                    ]);
                            }

                        });
    }

    public function dealPause()
    {

    }

    public function dealStop()
    {

    }
}
